package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiPager;
import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.*;
import cn.com.yx.ms.domain.dev.DevCatalogMapModel;
import cn.com.yx.ms.domain.dev.DevNameModel;
import cn.com.yx.ms.domain.program.CatalogModel;
import cn.com.yx.ms.domain.release.ReleaseModel;
import cn.com.yx.ms.domain.release.ReleaseStyleModel;
import cn.com.yx.ms.domain.release.ReleaseStyleModelControlModel;
import cn.com.yx.ms.domain.stl.*;
import cn.com.yx.ms.persistence.*;
import cn.com.yx.ms.service.IDevService;
import cn.com.yx.ms.service.IReleaseService;
import cn.com.yx.ms.service.IUserContextService;
import cn.yx.framework.configuration.ApiCode;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.util.PageUtil;
import cn.yx.framework.view.ApiResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 发布式样管理相关接口实现
 */
@Service
@Transactional
public class ReleaseServiceImpl implements IReleaseService {

    @Resource
    private StlMainMapper stlMainMapper;
    @Resource
    private StlDevMapMapper stlDevMapMapper;
    @Resource
    private StlModelMainMapMapper stlModelMainMapMapper;
    @Resource
    private ModelMainMapper modelMainMapper;
    @Resource
    private StlModelControlMapMapper stlModelControlMapMapper;
    @Resource
    private SysOrgMapper sysOrgMapper;
    @Resource
    private JmControlMapMapper jmControlMapMapper;
    @Resource
    private ModelControlMapper modelControlMapper;
    @Resource
    private JmMainMapper jmMainMapper;
    @Resource
    private IDevService iDevService;
    @Resource
    private IUserContextService iUserContextService;


    @Resource
    private DevCatalogMapper devCatalogMapper;

    /**
     * 查询式样
     *
     * @param query
     * @return
     */
    @Override
    public List<StlMainModel> findStlMain(ApiQueryBase query) {
        // 调用查询式样接口
        return stlMainMapper.findStlMain(query);
    }

    /**
     * 删除式样
     *
     * @param guids 式样id组
     * @return
     */
    @Override
    public ApiResult removeStlMain(String guids) {
        List<String> guidList = new ArrayList<String>();

        for (String guid : guids.split(",")) {
            guidList.add(guid);

            // 判断该式样是否有设备进行关联
            String rt = stlDevMapMapper.relationCheck(guid);

            if (null != rt && Integer.parseInt(rt) > 0) {
                StlMain stlMain=stlMainMapper.selectByPrimaryKey(guid);
                return new ApiResult(AppConstant.MSG_FAILURE, false,  stlMain.getName()    + "有设备绑定,请先移除设备", null);
            }
        }

        // 删除式样模板关系表相关
        stlModelMainMapMapper.updateByStyleid(guidList);

        // 删除式样设备关系表相关

        // 删除式样主体表
        if (stlMainMapper.updateByGuid(guidList) == 0) {
            return new ApiResult(AppConstant.MSG_FAILURE, false, "删除式样失败", null);
        }
        return new ApiResult(AppConstant.MSG_SUCCESS, true, "删除式样成功", null);
    }

    /**
     * 根据id获取模板
     *
     * @param guids 模板id组
     * @return
     */
    @Override
    public ApiResult getAllModelMain(String guids) {

        // 解析模板id
        List<String> list = new ArrayList<String>();
        if (!StringUtils.isEmpty(guids)) {
            for (String guid : guids.split(",")) {
                list.add(guid);
            }
        }

        // 调用模板接口
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "获取模板成功", modelMainMapper.findAllModelMainList(list));
    }

    /**
     * 新增式样
     *
     * @return
     */
    @Override
    public ApiResult addStlMain(StlMainModel stlMainModel) {
        String guid = UUID.randomUUID().toString();

        Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))");

        // 设备集合做成
        String[] devs = stlMainModel.getDevs().split(",");
        for (String dev : devs) {
            // 式样设备关联接口调用,如果存在 则删除,不存在添加
            int rt = stlDevMapMapper.devExistCheck(dev);
            if (rt > 0) {
                // isdeleted 更新为1
                stlDevMapMapper.saveOrUpdate(dev);
            }
            // 添加新式样设备关联
            if(StringUtils.isNotBlank(dev)) {
                stlDevMapMapper.insertDevMap(dev, guid, UUID.randomUUID().toString());
            }
        }
        // 式样主表新规
        StlMain stlMain = new StlMain();
        // 系统时间
        Date date = new Date();
        stlMain.setGuid(guid);
        // 式样说明
        stlMain.setMemo(stlMainModel.getMemo());
        // 式样名称
        stlMain.setName(stlMainModel.getName());
        // 新增系统时间
        stlMain.setCreatetime(date);
        // 新增式样接口调用
        int rt = stlMainMapper.insertSelective(stlMain);
        if (rt == 1) {
            // 式样模板栏目关系新规
            StlModelControlMap stlModelControlMap = new StlModelControlMap();
            // 式样id
            stlModelControlMap.setStyleid(guid);
            List<StlModelControlModel> stlModelControlModelList = stlMainModel.getModels();
            for (StlModelControlModel stlModelControlModel : stlModelControlModelList) {
                stlModelControlMap.setModelid(stlModelControlModel.getModelid());
                // 式样模板关系对象
                StlModelMainMap stlModelMainMap = new StlModelMainMap();
                stlModelMainMap.setGuid(UUID.randomUUID().toString());
                // 模板id
                stlModelMainMap.setModelid(stlModelControlModel.getModelid());
                // 式样id
                stlModelMainMap.setStyleid(guid);
                // 是否默认模板
                stlModelMainMap.setIsdefault(stlModelControlModel.getIsdefault());
                // 栏目管理授权相关Bean.
                List<StlControlModel> stlControlModels = stlModelControlModel.getControlModelList();
                for (StlControlModel stlControlModel : stlControlModels) {

                    // modify by wangwei 17-06-29
                    String regioncode = stlControlModel.getAreano();
                    Matcher matcher = pattern.matcher(regioncode);
                    if(matcher.find()){
                        regioncode = matcher.group();
                    }

                    stlModelControlMap.setGuid(UUID.randomUUID().toString());
                    // 栏目id
                    stlModelControlMap.setControlid(stlControlModel.getControlid());
                    // 管理授权id
                    stlModelControlMap.setOrgid(stlControlModel.getOrgid());
                    // 区域代码
                    stlModelControlMap.setRegioncode(regioncode);
                    // 式样,模板,栏位关系接口调用
                    stlModelControlMapMapper.insertSelective(stlModelControlMap);
                }
                // 式样,模板接口调用
                stlModelMainMapMapper.insertSelective(stlModelMainMap);
            }
        } else {
            return new ApiResult().success(AppConstant.MSG_FAILURE, "新增式样失败", null);
        }

        return new ApiResult().success(AppConstant.MSG_SUCCESS, "新增式样成功", null);
    }

    /**
     * 更新式样信息
     *
     * @param stlMainModel
     * @return
     */
    @Override
    public ApiResult updateStlMain(StlMainModel stlMainModel) {
        // 系统时间
        Date date = new Date();
//        String guid = UUID.randomUUID().toString();
        // 式样设备关联
        StlDevMap stlDevMap = new StlDevMap();

        // 获取当前式样下关联的设备
        List<StlDevMap> stlDevMaps = getDevsByStyleId(stlMainModel.getGuid());
        if (stlDevMaps != null && stlDevMaps.size() > 0) {
            for (int i = 0; i < stlDevMaps.size(); i++) {
                // stlDevMapMapper.setDeletedByStyleIdAndDevId(stlMainModel.getGuid(), stlDevMaps.get(i).getDevid());
                stlDevMapMapper.deletedMapByDevId(stlDevMaps.get(i).getDevid());
            }
        }

        // 设备集合做成
        String[] devs = stlMainModel.getDevs().split(",");

//        // 删除当前选中设备记录
//        for (String dev : devs) {
//            stlDevMapMapper.deletedMapByDevId(dev);
//        }

        for (String dev : devs) {
            // 添加新式样设备关联
            if(StringUtils.isNotBlank(dev)) {
                stlDevMapMapper.deletedMapByDevId(dev);
                stlDevMapMapper.insertDevMap(dev, stlMainModel.getGuid(), UUID.randomUUID().toString());
            }
        }
        // 式样主表更新
        StlMain stlMain = new StlMain();
        // 式样说明
        stlMain.setMemo(stlMainModel.getMemo());
        // 式样名称
        stlMain.setName(stlMainModel.getName());
        // 式样id
        stlMain.setGuid(stlMainModel.getGuid());

        Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))");

        // 新增式样接口调用
        int rt = stlMainMapper.updateByPrimaryKeySelective(stlMain);
        if (rt == 1) {
            // 式样模板栏目关系更新
            StlModelControlMap stlModelControlMap = new StlModelControlMap();
            // 式样id
            stlModelControlMap.setStyleid(stlMainModel.getGuid());
            // 式样模板栏目关系删除
            stlModelControlMapMapper.delByGuid(stlMainModel.getGuid());
            // 式样模板关系删除
            stlModelMainMapMapper.delByGuid(stlMainModel.getGuid());
            List<StlModelControlModel> stlModelControlModelList = stlMainModel.getModels();
            for (StlModelControlModel stlModelControlModel : stlModelControlModelList) {
                stlModelControlMap.setModelid(stlModelControlModel.getModelid());
                // 式样模板关系对象
                StlModelMainMap stlModelMainMap = new StlModelMainMap();
                stlModelMainMap.setGuid(UUID.randomUUID().toString());
                // 模板id
                stlModelMainMap.setModelid(stlModelControlModel.getModelid());
                // 式样id
                stlModelMainMap.setStyleid(stlMainModel.getGuid());
                // 是否默认模板
                stlModelMainMap.setIsdefault(stlModelControlModel.getIsdefault());
                // 栏目管理授权相关Bean.
                List<StlControlModel> stlControlModels = stlModelControlModel.getControlModelList();
                for (StlControlModel stlControlModel : stlControlModels) {

                    // modify by wangwei 17-06-29
                    String regioncode = stlControlModel.getAreano();
                    Matcher matcher = pattern.matcher(regioncode);
                    if(matcher.find()){
                        regioncode = matcher.group();
                    }


                    stlModelControlMap.setGuid(UUID.randomUUID().toString());
                    // 栏目id
                    stlModelControlMap.setControlid(stlControlModel.getControlid());
                    // 管理授权id
                    stlModelControlMap.setOrgid(stlControlModel.getOrgid());
                    // 区域代码
                    stlModelControlMap.setRegioncode(regioncode);
                    // 式样,模板,栏位关系接口调用
                    stlModelControlMapMapper.insertSelective(stlModelControlMap);
                }
                // 式样,模板接口调用
                stlModelMainMapMapper.insertSelective(stlModelMainMap);
            }
        }
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "更新式样成功", null);
    }


    /**
     * 获取管理授权单位一览
     *
     * @return
     */
    @Override
    public ApiResult getOrgList() {
        ApiResult apiResult = new ApiResult();
        apiResult.setSucc(true);
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "获取管理授权单位一览成功", sysOrgMapper.selectAllOrg());
    }

    /**
     * 获取节目发布一览
     *
     * @param stlJmModel 节目发布参数
     * @return
     */
    @Override
    public ApiResult getAllJmMain(StlJmModel stlJmModel) {
        // 获取节目发布一览接口调用
        List<StlJmControlModel> list = stlMainMapper.selectALLJmMain(stlJmModel);

        // 返回结果
        List<StlJmControlModel> returnList = new ArrayList<StlJmControlModel>();
        String styleid = "";

        // 节目发布用Bean
        StlJmControlModel model = new StlJmControlModel();

        // 子集保存用lists
        List<StlJmControlModel> subList = new ArrayList<StlJmControlModel>();

        for (int i = 0; i < list.size(); i++) {
            StlJmControlModel stlJmControlModel = list.get(i);
            if (StringUtils.isEmpty(styleid)) {
                styleid = stlJmControlModel.getStyleid();
                model.setStyleid(styleid);
                model.setStylename(stlJmControlModel.getStylename());
                model.setModelname(stlJmControlModel.getModelname());
                model.setConcount(stlJmControlModel.getConcount());
                model.setDevcount(stlJmControlModel.getDevcount());

                StlJmControlModel simpleModel = new StlJmControlModel();
                simpleModel.setControlname(stlJmControlModel.getControlname());
                simpleModel.setControlid(stlJmControlModel.getControlid());
                simpleModel.setSourcetype(stlJmControlModel.getSourcetype());
                simpleModel.setModelid(stlJmControlModel.getModelid());
                simpleModel.setJmid(stlJmControlModel.getJmid());
                simpleModel.setTitle(stlJmControlModel.getTitle());
                simpleModel.setOrgname(stlJmControlModel.getOrgname());
                simpleModel.setRegioncode(stlJmControlModel.getRegioncode());

                // 只显示节目类区域
                if (stlJmControlModel.getSourcetype() != null) {
                    if (stlJmControlModel.getSourcetype().equals("0") || stlJmControlModel.getSourcetype().equals("1")) {
                        subList.add(simpleModel);
                    }
                }

                // 最后一项
                if (i == list.size() - 1) {
                    model.setStlJmControlModels(subList);
                    returnList.add(model);
                }
                continue;
            }

            if (styleid.equals(stlJmControlModel.getStyleid())) {
                StlJmControlModel simpleModel = new StlJmControlModel();
                simpleModel.setControlname(stlJmControlModel.getControlname());
                simpleModel.setControlid(stlJmControlModel.getControlid());
                simpleModel.setModelid(stlJmControlModel.getModelid());
                simpleModel.setSourcetype(stlJmControlModel.getSourcetype());
                simpleModel.setJmid(stlJmControlModel.getJmid());
                simpleModel.setTitle(stlJmControlModel.getTitle());
                simpleModel.setOrgname(stlJmControlModel.getOrgname());
                simpleModel.setRegioncode(stlJmControlModel.getRegioncode());
                if (stlJmControlModel.getSourcetype() != null) {
                    if (stlJmControlModel.getSourcetype().equals("0") || stlJmControlModel.getSourcetype().equals("1")) {
                        subList.add(simpleModel);
                    }
                }
            } else {
                model.setStlJmControlModels(subList);
                returnList.add(model);

                model = new StlJmControlModel();
                subList = new ArrayList<StlJmControlModel>();

                model.setStyleid(stlJmControlModel.getStyleid());
                model.setStylename(stlJmControlModel.getStylename());
                model.setModelname(stlJmControlModel.getModelname());
                model.setConcount(stlJmControlModel.getConcount());
                model.setDevcount(stlJmControlModel.getDevcount());

                StlJmControlModel simpleModel = new StlJmControlModel();
                simpleModel.setControlname(stlJmControlModel.getControlname());
                simpleModel.setControlid(stlJmControlModel.getControlid());
                simpleModel.setSourcetype(stlJmControlModel.getSourcetype());
                simpleModel.setModelid(stlJmControlModel.getModelid());
                simpleModel.setJmid(stlJmControlModel.getJmid());
                simpleModel.setTitle(stlJmControlModel.getTitle());
                simpleModel.setOrgname(stlJmControlModel.getOrgname());
                simpleModel.setRegioncode(stlJmControlModel.getRegioncode());
                if (stlJmControlModel.getSourcetype() != null) {
                    if (stlJmControlModel.getSourcetype().equals("0") || stlJmControlModel.getSourcetype().equals("1")) {
                        subList.add(simpleModel);
                    }
                }

                styleid = stlJmControlModel.getStyleid();
            }

            // 最后一项
            if (i == list.size() - 1) {
                model.setStlJmControlModels(subList);
                returnList.add(model);
            }
        }

        // 翻页对象构建
        PageHelper.startPage(stlJmModel.getPage_pi(), stlJmModel.getPage_ps(), true);
        List<StlJmControlModel> PageList = PageUtil.getPageList(stlJmModel.getPage_ps(), stlJmModel.getPage_pi(), returnList);
        ApiPager<StlJmControlModel> apiPager = new ApiPager<StlJmControlModel>(stlJmModel.getPage_ps(),
                stlJmModel.getPage_pi(),
                PageList.size(),
                PageList);
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "获取节目发布一览成功", apiPager);
    }

    /**
     * 获取关联界面列表
     *
     * @param controlId
     * @return
     */
    @Override
    public ApiResult getAllJmByControlid(String controlId, ApiQueryBase query) {
        ModelControl modelControl = modelControlMapper.selectByPrimaryKey(controlId);
        query.getConditions().put("sort", modelControl.getSourcetype().toString());
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "获取节目列表成功", jmControlMapMapper.selectAllJm(query));
    }


    /**
     * 新增节目
     *
     * @param stlMainModel 节目素材对象
     * @return
     */
    @Override
    public ApiResult addJmMain(StlScModel stlMainModel) {
        JmControlMap jmControlMap = new JmControlMap();
        jmControlMap.setGuid(UUID.randomUUID().toString());
        jmControlMap.setControlid(stlMainModel.getControlid());
        jmControlMap.setJmid(stlMainModel.getGuid());

        // 新增节目接口调用
        if (jmControlMapMapper.insertSelective(jmControlMap) == 1) {
            return new ApiResult().success(AppConstant.MSG_SUCCESS, "新增节目成功", null);
        }
        return new ApiResult().success(AppConstant.MSG_FAILURE, "获取节目失败", null);
    }

    /**
     * 更新节目
     *
     * @param stlJmMapModel 节目素材对象
     * @return
     */
    @Override
    public ApiResult updateJmMain(StlJmMapModel stlJmMapModel) {
        // 更新节目接口调用
        jmControlMapMapper.deleteJmControlMap(stlJmMapModel.getModelid(),
                stlJmMapModel.getControlid(),
                stlJmMapModel.getRegioncode());

        JmControlMap jmControlMap = new JmControlMap();
        jmControlMap.setGuid(UUID.randomUUID().toString());
        jmControlMap.setModelid(stlJmMapModel.getModelid());
        jmControlMap.setControlid(stlJmMapModel.getControlid());
        jmControlMap.setRegioncode(stlJmMapModel.getRegioncode());
        jmControlMap.setJmid(stlJmMapModel.getJmid());
        jmControlMap.setCreatetime(new Date());

        int count = jmControlMapMapper.insert(jmControlMap);

        if (count > 0) {
            return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "更新节目成功");
        }
        return new ApiResult(AppConstant.MSG_FAILURE, false, "更新节目失败");
    }

    /**
     * 根据式样id获取栏目信息
     *
     * @param styleid 式样id
     * @return
     */
    @Override
    public ApiResult getJmByStyleid(String styleid) {
        ApiResult apiResult = new ApiResult();

        // 同步栏目接口调用
        List<StlJmControlModel> stlJmControlModel = stlMainMapper.getJmByStyleid(styleid);

        // 同步设备接口调用
        List<DevNameModel> devNameModel = stlMainMapper.getDevSemByStyleid(styleid);

        DevCatalogMapModel mapModel = new DevCatalogMapModel();

        mapModel.setDevNameModels(devNameModel);
        mapModel.setStlJmControlModel(stlJmControlModel);

        apiResult.setData(mapModel);
        apiResult.setSucc(true);

        return new ApiResult().success(AppConstant.MSG_SUCCESS, "式样加载成功", apiResult);
    }

    /**
     * 根据式样id获取栏目信息
     *
     * @param styleid 式样id
     * @return
     */
    @Override
    public ApiResult getDevByStyleid(String styleid) {
        ApiResult apiResult = new ApiResult();

        // 同步设备接口调用
        List<DevCatalog> devNameModel = stlMainMapper.getDevByStyleid(styleid);

        DevCatalog devCatalog = devCatalogMapper.selectByPrimaryKey("root");
        List<CatalogModel> devCatalogModels = new ArrayList<CatalogModel>();

        //初始化根节点
        CatalogModel root = new CatalogModel();
        root.setId(devCatalog.getGuid());
        root.setName(devCatalog.getName());
        root.setNumber(devCatalog.getNumber());
        root.setChildren(new ArrayList<CatalogModel>());

        BuildDevCatalogTree(root, devNameModel);

        if (root.getChildren() != null && root.getChildren().size() != 0) {
            root.setIsleaf(0);
        } else {
            root.setIsleaf(1);
        }

        devCatalogModels.add(root);

        apiResult.setData(devCatalogModels);
        apiResult.setSucc(true);


        return new ApiResult().success(AppConstant.MSG_SUCCESS, "设备加载成功", apiResult);
    }

    @Override
    public List<StlDevMap> getDevsByStyleId(String styleId) {
        List<StlDevMap> stlDevMaps = stlDevMapMapper.getDevByStyleId(styleId);
        return stlDevMaps;
    }

    /**
     * 设备树结构做出
     *
     * @param devNameModels 子节点list
     */
    private void BuildDevCatalogTree(CatalogModel node, List<DevCatalog> devNameModels) {
        for (DevCatalog devCatalog :
                devNameModels) {
            if (devCatalog != null && devCatalog.getParentid() != null && node.getId() != null && devCatalog.getParentid().equals(node.getId())) {
                CatalogModel child = new CatalogModel();
                child.setId(devCatalog.getGuid());
                child.setName(devCatalog.getName());
                child.setParentid(devCatalog.getParentid());
                child.setNumber(devCatalog.getNumber());
//                child.setOrderindex(devCatalog.getOrderindex());
                child.setChildren(new ArrayList<CatalogModel>());
                node.getChildren().add(child);

                //递归调用
                BuildDevCatalogTree(child, devNameModels);
                if (child.getChildren() != null && child.getChildren().size() != 0) {
                    child.setIsleaf(0);
                } else {
                    child.setIsleaf(1);
                }
            }
        }
    }

    /**
     * 设备同步选择式样
     *
     * @return
     */
    @Override
    public ApiResult getAllStyles() {
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "式样获取成功", stlMainMapper.getAllStyles());
    }

    /**
     * 根据式样id获取式样详细信息
     *
     * @param styleid 式样id
     * @return
     */
    @Override
    public ApiResult getAllJmByStyleid(String styleid) {
        StlMainDevModel stlMainDevModel = new StlMainDevModel();

        stlMainDevModel.setStlMainUpdateModels(stlMainMapper.getAllJmByStyleid(styleid));
        stlMainDevModel.setDevs(stlDevMapMapper.selectByStyleId(styleid));
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "式样获取成功", stlMainDevModel);
    }

    /**
     * 根据节目id获取素材列表
     *
     * @param jmid 节目id
     * @return
     */
    @Override
    public ApiResult getScByJmid(String jmid) {
        List<StlScModel> models = jmControlMapMapper.getScByJmid(jmid);
        return new ApiResult().success(AppConstant.MSG_SUCCESS, "式样素材成功", models);
    }

    // region << 发布管理 >>

    public ApiPager<ReleaseStyleModel> findPageReleaseStyles(ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("stylename", request.getParameter("stylename"));


        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        List<ReleaseStyleModel> releaseStyleModelList = stlMainMapper.findAllReleaseStyleModels(query);
        for (ReleaseStyleModel releaseStyleModel : releaseStyleModelList) {
            releaseStyleModel.setDefaultmodelname(releaseStyleModel.getDefaultmodelname() + "(" + releaseStyleModel.getModelno() + ")");
        }
        Page<ReleaseStyleModel> page = (Page<ReleaseStyleModel>) releaseStyleModelList;
        ApiPager<ReleaseStyleModel> apiPager = new ApiPager<>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());

        // 获取所有模板区域
        List<ReleaseStyleModelControlModel> controls = stlMainMapper.findAllReleaseStyleModelControlModel();

        String orgid = iUserContextService.getUserContext().getOrgid();
        String userName = iUserContextService.getUserContext().getUsername();
        // 筛选出默认模板的区域
        // 权限说明： demo或admin用户不需要判断权限,以外用户需要判断orgid是否为空及orgid是否就是本单位
        if (apiPager.getList() != null) {
            for (int i = 0; i < apiPager.getList().size(); i++) {
                apiPager.getList().get(i).setControls(new ArrayList<>());
                if (controls != null) {
                    for (int j = 0; j < controls.size(); j++) {
                        if ((apiPager.getList().get(i).getStyleid().equals(controls.get(j).getStyleid())
                                && controls.get(j).getModelid().equals(apiPager.getList().get(i).getDefaultmodelid()))
                                && ("demo".equals(userName) || "admin".equals(userName) || ( !"demo".equals(userName) && !"admin".equals(userName) && (StringUtils.isEmpty(controls.get(j).getOrgid()) || orgid.equals(controls.get(j).getOrgid()))))) {
                            apiPager.getList().get(i).getControls().add(controls.get(j));
                        }
                    }
                }
            }
        }

        return apiPager;
    }

    /**
     * 根据设备编号找到该设备的关联式样
     *
     * @param query
     * @param request
     * @return
     */
    @Override
    public ApiPager<ReleaseStyleModel> findPageResleaseStylesByDevsn(ApiQueryBase query, HttpServletRequest request) {
        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        //query.getConditions().put("stylename", request.getParameter("stylename"));
        query.getConditions().put("devsn", request.getParameter("devsn"));
        System.out.println("设备编号:" + request.getParameter("devsn"));
//        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        List<ReleaseStyleModel> releaseStyleModelList = stlMainMapper.findReleaseStyleModelsByDevsn(query);
        for (ReleaseStyleModel releaseStyleModel : releaseStyleModelList) {
            releaseStyleModel.setDefaultmodelname(releaseStyleModel.getDefaultmodelname() + "(" + releaseStyleModel.getModelno() + ")");
        }
        Page<ReleaseStyleModel> page = (Page<ReleaseStyleModel>) releaseStyleModelList;
        ApiPager<ReleaseStyleModel> apiPager = new ApiPager<>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());
//
        // 获取所有模板区域
        List<ReleaseStyleModelControlModel> controls = stlMainMapper.findAllReleaseStyleModelControlModel();

        // 筛选出默认模板的区域
        if (apiPager.getList() != null) {
            for (int i = 0; i < apiPager.getList().size(); i++) {
                apiPager.getList().get(i).setControls(new ArrayList<>());
                if (controls != null) {
                    for (int j = 0; j < controls.size(); j++) {
                        if ((apiPager.getList().get(i).getStyleid().equals(controls.get(j).getStyleid())
                                && controls.get(j).getModelid().equals(apiPager.getList().get(i).getDefaultmodelid()))
                                ) {
                            apiPager.getList().get(i).getControls().add(controls.get(j));
                        }
                    }
                }
            }
        }
//
        return apiPager;
//        return null;
    }

    public List<ReleaseStyleModel> findReleaseStyles(ApiQueryBase apiQueryBase) {

        List<ReleaseStyleModel> result = new ArrayList<>();
        // 获取已发布的式样信息
        List<ReleaseStyleModel> styles = stlMainMapper.findAllReleaseStyleModels(apiQueryBase);

        // 获取所有模板区域
        List<ReleaseStyleModelControlModel> controls = stlMainMapper.findAllReleaseStyleModelControlModel();

        // 筛选出默认模板的区域
        if (styles != null) {
            for (int i = 0; i < styles.size(); i++) {
                styles.get(i).setControls(new ArrayList<>());
                if (controls != null) {
                    for (int j = 0; j < controls.size(); j++) {
                        if (controls.get(j).getModelid().equals(styles.get(i).getDefaultmodelid())) {
                            styles.get(i).getControls().add(controls.get(j));
                        }
                    }
                }
                result.add(styles.get(i));
            }
        }

        return result;
    }

    public ApiCode releaseProgram(ReleaseModel releaseModel,boolean issync) throws Exception {
        ApiCode apiCode = ApiCode.APP_100200;

        int sendWsType = -1;
        JmMain jm = jmMainMapper.selectByPrimaryKey(releaseModel.getJmid());
        if (jm != null) {
            if (jm.getSort().equals(0)) {
                sendWsType = 0;
            } else {
                sendWsType = 1;
            }
        }

        // modify by wangwei 17-06-29
        List<String> devs=new ArrayList<String>();
        List<DevNameModel> devNameModels=releaseModel.getDevs();
        for (DevNameModel devNameModel:devNameModels) {
            devs.add(devNameModel.getDevid());
        }
        //保存区域节目
        apiCode = saveProgram(releaseModel);
        // 同步设备并ws推送
        if(issync) {
            if (devs != null && devs.size() > 0) {
                for (String devid : devs) {
                    iDevService.syncDevTemplate(devid, releaseModel.getStyleid(), true, sendWsType);
                }
            }
        }

        return apiCode;
    }

    // endregion

    public ApiCode saveProgram(ReleaseModel releaseModel) throws Exception {
        ApiCode apiCode = ApiCode.APP_100200;

        String regioncode = releaseModel.getRegioncode();

        Pattern pattern = Pattern.compile("(?<=\\()(.+?)(?=\\))");
        Matcher matcher = pattern.matcher(regioncode);
        if(matcher.find()){
            regioncode = matcher.group();
        }

        // 更换栏目对应的节目的ID
        jmControlMapMapper.deleteJmControlMap(releaseModel.getModelid(),
                releaseModel.getControlid(),
                regioncode);
        JmControlMap jmControlMap = new JmControlMap();
        jmControlMap.setGuid(UUID.randomUUID().toString());
        jmControlMap.setJmid(releaseModel.getJmid());
        jmControlMap.setControlid(releaseModel.getControlid());
        jmControlMap.setModelid(releaseModel.getModelid());
        jmControlMap.setCreatetime(new Date());
        jmControlMap.setRegioncode(regioncode);
        jmControlMap.setStyleid(releaseModel.getStyleid());
        jmControlMapMapper.insert(jmControlMap);
        return apiCode;
    }
}
